﻿function FindProxyForURL(url, host) 
{
	url = url.toLowerCase();
	host = host.toLowerCase();
	var resolved_ip = dnsResolve(host);

// If URL has no dots in host name, send traffic direct.
	if (isPlainHostName(host))
	return "DIRECT";

// If IP address is internal or hostname resolves to internal IP, send direct.
	else if (isInNet(resolved_ip, "10.0.0.0", "255.0.0.0") ||
		isInNet(resolved_ip, "172.16.0.0",  "255.240.0.0") ||
		isInNet(resolved_ip, "192.168.0.0", "255.255.0.0") ||
		isInNet(resolved_ip, "127.0.0.0", "255.255.255.0")
		)
	return "DIRECT";

	else if (shExpMatch(url, "https://*")||
		shExpMatch(url, "ftp://*")
		)
	return "DIRECT";
	
	else
	{
		if(myarray==null)
		{
			CnIpRange();
		}
		else
		{
			for (var ip in myArray)
			{
				//如果是国内网段，直接接连。
				if (isInNet(resolved_ip, myArray[ip][0], myArray[ip][1]))
				return "DIRECT";
				else return"PROXY 127.0.0.1:8000";
			}
		}
	}
}

var myArray=new Array();
function CnIpRange()
{
	var m=0
	var oXML=new XMLHttpRequest();
	oXML.open("GET","http://ftp.apnic.net/apnic/dbase/data/country-ipv4.lst",false);
	oXML.send(null);  //send要有null没有就错了
	var iplist=oXML.responseText.split(/\r?\n/);

	for (var i in iplist)
	{
		if (iplist [i].substr(0,1)!="#")
		{
			var ipline=iplist [i].split(":");
			if( ipline[2].replace(/(^\s*)|(\s*$)/g,"")=="cn")
			{
				myArray[m]=new Array();
				myArray[m][0]=ipline[0].split("-")[0].replace(/(^\s*)|(\s*$)/g,"");
				myArray[m][1]=ipline[0].split("-")[1].replace(/(^\s*)|(\s*$)/g,"");
				m++;
			}
		}
	}
}
